#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>

int main() {
    char buffer[64];
    // create a server
    int serv_fd = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in serv_addr;
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    serv_addr.sin_port = htons(1234);
    bind(serv_fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));

    // wait for clnt sending requests;
    listen(serv_fd, 20);
    
    // accept requests from clients;
    struct sockaddr_in clnt_addr;
    socklen_t clnt_len;
    int clnt_fd;
    while(1) {
	    memset(buffer, 0, sizeof(buffer));
	    clnt_fd = accept(serv_fd, (struct sockaddr*)&clnt_addr, &clnt_len);

	    // read data and repeat;
	    read(clnt_fd, buffer, sizeof(buffer));
	    printf("ECHO: %s\n", buffer);
	    // echo
	    write(clnt_fd, buffer, sizeof(buffer));

	    if(!strcmp(buffer, "exit\n")) {
		    close(clnt_fd);
		    break;
	    }

	    close(clnt_fd);
    
    }
    close(serv_fd);

    return 0;
}
